﻿using System;
using System.Threading.Tasks;
using System.Collections.Generic;

using CtpApi;
using CtpApi.Struct;

namespace TraderClient.Logic.CTP
{
    /// <summary>
    /// 行情数据接口操作类
    /// </summary>
    public class MdApi
    {
        /// <summary>
        /// 初始化并异步运行行情数据接口
        /// </summary>
        public MdApi()
        {
            Init();
        }

        /// <summary>
        /// 获取行情数据队列中的数据（先进先出）
        /// </summary>
        /// <returns>深度行情数据结构（没有数据则返回null）</returns>
        public CThostFtdcDepthMarketDataField GetDepthMarketData()
        {
            return (marketDataQueue.Count > 0) ? marketDataQueue.Dequeue() : null;
        }

        // 释放行情数据接口对象
        ~MdApi()
        {
            //释放接口对象
            mdApi.Release();

            //清除队列数据
            marketDataQueue.Clear();
        }

        /**************************** Private ****************************/

        /// <summary>
        /// 行情数据接口对象
        /// </summary>
        private CtpMdApi mdApi;

        /// <summary>
        /// 请求序号
        /// </summary>
        private int requestID = 0;

        /// <summary>
        /// 行情数据队列
        /// </summary>
        private Queue<CThostFtdcDepthMarketDataField> marketDataQueue;

        /// <summary>
        /// 初始化并运行行情数据接口
        /// </summary>
        private void Init()
        {
            //生成行情数据队列
            marketDataQueue  = new Queue<CThostFtdcDepthMarketDataField>();

            //初始化接口对象并注册前置机地址
            mdApi = new CtpMdApi();
            mdApi.RegisterFront(@"tcp://asp-sim2-md1.financial-trading-platform.com:26213");
            //mdApi.RegisterFront(@"tcp://cifco-md1.financial-trading-platform.com:41213");

            //注册接口回调事件
            mdApi.CtpMdEvents.OnFrontConnected      += this.OnFrontConnected;
            mdApi.CtpMdEvents.OnRspUserLogin        += this.OnRspUserLogin;
            mdApi.CtpMdEvents.OnRspSubMarketData    += this.OnRspSubMarketData;
            mdApi.CtpMdEvents.OnRtnDepthMarketData  += this.OnRtnDepthMarketData;

            //初始化并运行
            mdApi.Init();
            Task.Factory.StartNew(mdApi.Join);
        }

        /// <summary>
        /// 连接前置机
        /// </summary>
        private void OnFrontConnected()
        {
            CThostFtdcReqUserLoginField loginField = new CThostFtdcReqUserLoginField();

            string BROKER = "4030";
            string ACCOUNT = "80002863";
            string PASSWORD = "888888";

            loginField.BrokerID = BROKER;
            loginField.UserID = ACCOUNT;
            loginField.Password = PASSWORD;

            mdApi.ReqUserLogin(loginField, requestID++);
        }

        /// <summary>
        /// 用户登录应答
        /// </summary>
        private void OnRspUserLogin(CThostFtdcRspUserLoginField rspUserLoginfield, CThostFtdcRspInfoField rspInfoField, int nRequestID, bool bIsLast)
        {
            TraderClient.Models.DisplayInstruments[] instruments = WAF.EntityFramework.EntityAction.Select<TraderClient.Models.DisplayInstruments>();

            string[] instrument = new string[instruments.Length];

            for (int i = 0; i < instruments.Length; i++)
            {
                instrument[i] = instruments[i].InstrumentID;
            }

            mdApi.SubscribeMarketData(instrument, instrument.Length);
        }

        private void OnRspSubMarketData(CThostFtdcSpecificInstrumentField pSpecificInstrument, CThostFtdcRspInfoField pRspInfo, int nRequestID, bool bIsLast)
        {
            
        }

        /// <summary>
        /// 将接收到的深度行情数据结构放入队列
        /// </summary>
        /// <param name="pDepthMarketData">深度行情数据结构</param>
        private void OnRtnDepthMarketData(CThostFtdcDepthMarketDataField pDepthMarketData)
        {
            marketDataQueue.Enqueue(pDepthMarketData);
        }
    }
}
